package com.dubbo.protocol.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.concurrent.CountDownLatch;


/**
 * 客户端逻辑
 */
public class ClientHandler extends ChannelInboundHandlerAdapter
{
    private CountDownLatch cdl = null;
    //请求对象
    Object obj = null;
    //返回对象
    Object responseObj = null;

    public ClientHandler(Object obj)
    {
        cdl = new CountDownLatch(1);
        this.obj = obj;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
        // Send the message to Server
        ctx.writeAndFlush(obj);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
    {
        // you can use the Object from Server here
        System.out.println("client read return:" + msg);

        responseObj = msg;

        ctx.close();
        cdl.countDown();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception
    {
        ctx.flush();
    }


    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, Throwable cause) throws Exception
    {

        ctx.close();
    }


    public Object getResponse()
    {
        try
        {
            cdl.await();
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        return responseObj;
    }
}

